import socket
import threading
import globalVar
import select
import modbus


# 新建Tcp/IP实例
def newTcpClient(ip, port, clientNum):
# 创建Socket时，AF_INET指定使用IPv4协议，如果要用更先进的IPv6，就指定为AF_INET6。S
# OCK_STREAM指定使用面向流的TCP协议
    n = 1
    globalVar.listSocState = []
    while n <= clientNum:
        mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #设置为非阻塞模式，非阻塞模式下，
        # 如果调用recv()没有发现任何数据，或send()调用无法立即发送数据，那么将引起socket.error异常。
         
        mySocket.connect((ip, port))
        mySocket.setblocking(0) 
        loginMsg = 'LOGIN-000220170820' + "%04d"%n
        no = n-1  #指明当前socket实例在listInsCode
        globalVar.listSocState.insert(no, True)   # Socket开启，将状态置true
        mySocket.send(bytes(loginMsg, encoding="utf8"))
        myThread = threading.Thread(target=clientRec, args=(mySocket, no))
        myThread.start()
        n +=1        
        
def clientRec(mySocket, no):
    print("进入接收线程")   
    buffer = []
  
    while globalVar.listSocState[no]:
        buffer = select.select([mySocket], [], [], 5)
        if buffer[0]:
            recData = mySocket.recv(1024)
            writeData = modbus.onProcData(recData)
            if writeData :
                mySocket.send(writeData) 
    print("关闭接收线程") 
    mySocket.close()
    

def CloseTcpClient(clientNum):
    while clientNum > 0:
        clientNum -=1
        globalVar.listSocState[clientNum] = socketClose = False

